package 牛客.链表;

import 剑指offer.ListNode;

import java.util.HashSet;
import java.util.Set;

public class BM15删除有序链表中重复的元素_I {
    public ListNode deleteDuplicates(ListNode head) {
        if (head==null || head.next==null) {
            return head;
        }

        ListNode cur=head;
        while (cur.next!=null) {
            //cur.next!=null  此判空只要是为了第一个if不发生空指针异常
            if (cur.val==cur.next.val) {
                cur.next=cur.next.next;
            }else {
                cur=cur.next;
            }
        }
        return head;
    }

    public ListNode deleteDuplicates1(ListNode head) {
        // write code here
        if (head==null || head.next==null) {
            return head;
        }
        Set<Integer> set=new HashSet<>();
        ListNode cur=head;
        ListNode pre=null;
        while (cur!=null) {
            if (!set.add(cur.val)) {
                //添加失败
                pre.next=cur.next;
            }else {
                pre=cur;
            }
            cur=cur.next;
        }
        return head;

    }
}
